package gateway.web;

import gateway.dtos.GatewayApi;
import gateway.event.RefreshRouteService;
import gateway.exception.GatewayApiException;
import gateway.exception.GatewayInsertException;
import gateway.pojo.GatewayApiDefine;
import gateway.service.GatewayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

@RestController
public class GatewayControllers {

    @Autowired
    private GatewayService gatewayService;


    @Autowired
    RefreshRouteService refreshRouteService;

    @RequestMapping("/refreshRoute")
    public String refreshRoute(){
        refreshRouteService.refreshRoute();
        return "refreshRoute";
    }

    @GetMapping("/getGateways")
    public List<GatewayApiDefine> getGateways(){
        return gatewayService.getGateways();
    }



    @PostMapping("/insert")
    public boolean insertTest(@Valid @RequestBody GatewayApi gatewayApi, BindingResult bindingResult){

        if (bindingResult.hasErrors()){
            throw new GatewayApiException();
        }

        GatewayApiDefine gatewayApiDefine =gatewayService.insertGateway(new GatewayApiDefine(gatewayApi));

        if (Objects.isNull(gatewayApiDefine)) {
            throw new GatewayInsertException();
        } else {
            return true;
        }
    }

}
